package com.easonji.admin.controller;

import javax.annotation.Resource;
import javax.validation.Valid;

import com.easonji.common.base.controller.BaseController;
import com.easonji.common.base.response.Response;
import com.easonji.common.base.response.enums.ResponseEnum;
import com.easonji.common.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.easonji.admin.form.RoleForm;
import com.easonji.admin.manager.AppManager;
import com.easonji.admin.manager.RoleManager;
import com.easonji.admin.query.RoleQuery;
import com.easonji.admin.service.RoleService;
import com.easonji.common.constant.Consts;
import com.easonji.common.constant.dictmap.RoleDict;
import com.easonji.common.constant.enums.message.MessageEnum;
import com.easonji.core.annotion.BussinessLog;
import com.easonji.core.annotion.Permission;
import com.easonji.core.log.LogObjectHolder;

/**
 * @ClassName: RoleController
 * @Description: 角色控制器
 * @Author: LiuJun
 * @date: 2018/07/30 14:06:36
 * @Version: 1.0
 * @Copyright: Copyright (c) 2018 - 2019
 */
@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {

    /**
     * 页面前缀
     */
    private final static String PREFIX = "system/role/";

    @Resource
    private RoleService roleService;

    @Resource
    private RoleManager roleManager;

    @Resource
    private AppManager appManager;

    /**
     * 跳转到角色首页
     */
    @Permission(Consts.ADMIN_ROLE_NAME)
    @GetMapping("")
    public String index(Model model) {
        model.addAttribute("appId", Consts.DEFAULT_APP_ID);
        return PREFIX + "role";
    }

    /**
     * 跳转到添加角色页面
     */
    @Permission(Consts.ADMIN_ROLE_NAME)
    @GetMapping("/to_add")
    public String toAdd(Model model) {
        model.addAttribute("appId", Consts.DEFAULT_APP_ID);
        return PREFIX + "role_add";
    }

    /**
     * 跳转到修改角色页面
     */
    @Permission(Consts.ADMIN_ROLE_NAME)
    @GetMapping("/to_update/{roleId}")
    public String toUpdate(@PathVariable Integer roleId, Model model) {
        Object result = roleService.queryRole(roleId);
        LogObjectHolder.me().set(result);
        model.addAttribute("role", result);
        return PREFIX + "role_edit";
    }

    /**
     * 跳转到角色分配页面
     */
    @Permission(Consts.ADMIN_ROLE_NAME)
    @GetMapping("/to_authorityAssign/{roleId}")
    public String authorityIndex(@PathVariable Integer roleId, Model model) {
        model.addAttribute("roleId", roleId);
        model.addAttribute("appId", roleManager.getAppIdById(roleId));
        model.addAttribute("appName", roleManager.getAppNameById(roleId));
        model.addAttribute("roleName", roleManager.getRoleNameById(roleId));
        return PREFIX + "role_authorityAssign";
    }

    /**
     * 查询角色列表
     */
    @ResponseBody
    @Permission
    @PostMapping("/list")
    public Object queryRoleList(RoleQuery roleQuery) {
        Object result = roleService.queryRoleList(roleQuery);
        return result;
    }

    /**
     * 添加角色
     */
    @ResponseBody
    @Permission(Consts.ADMIN_ROLE_NAME)
    @BussinessLog(value = "添加角色", key = "appId,name", dict = RoleDict.class)
    @PostMapping("/add")
    public Response addRole(@Valid RoleForm roleForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return failure(ResponseEnum.PARAMETER_ERROR);
        }
        int result = roleService.saveRole(roleForm);
        if (result == 0) {
            return failure(ResponseEnum.DATABASE_ERROR);
        }
        return success(ResponseEnum.SAVE_SUCCESS);
    }

    /**
     * 修改角色
     */
    @ResponseBody
    @Permission(Consts.ADMIN_ROLE_NAME)
    @BussinessLog(value = "修改角色", key = "appId,name", dict = RoleDict.class)
    @PostMapping("/update")
    public Response updateRole(@Valid RoleForm roleForm, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return failure(ResponseEnum.PARAMETER_ERROR);
        }
        int result = roleService.updateRole(roleForm);
        if (result == 0) {
            return failure(ResponseEnum.DATABASE_ERROR);
        }
        return success(ResponseEnum.UPDATE_SUCCESS);
    }

    /**
     * 删除角色
     */
    @ResponseBody
    @Permission(Consts.ADMIN_ROLE_NAME)
    @BussinessLog(value = "删除角色", key = "name", dict = RoleDict.class)
    @PostMapping("/remove")
    public Response removeRole(@RequestParam Integer roleId) {
        if (StringUtils.isEmpty(roleId)) {
            return failure(ResponseEnum.PARAMETER_ERROR);
        }
        // 不能删除超级管理员角色
        if (roleId.equals(Consts.ADMIN_ROLE_ID)) {
            return failure(MessageEnum.CANT_DELETE_ADMIN_ROLE.getCode(),
                    MessageEnum.CANT_DELETE_ADMIN_ROLE.getMessage());
        }
        String appName = roleManager.getAppNameById(roleId);
        String roleName = roleManager.getRoleNameById(roleId);
        LogObjectHolder.me().set(appName + Consts.HYPHEN + roleName);
        roleService.removeRole(roleId);
        return success(ResponseEnum.REMOVE_SUCCESS);
    }

    /**
     * 配置权限
     */
    @ResponseBody
    @Permission(Consts.ADMIN_ROLE_NAME)
    @BussinessLog(value = "配置权限", key = "appId,roleId,permissionIds", dict = RoleDict.class)
    @PostMapping("/setAuthority")
    public Response setAuthority(@RequestParam Integer appId, @RequestParam Integer roleId,
            @RequestParam String permissionIds) {
        if (StringUtils.isOneEmpty(roleId, permissionIds)) {
            return failure(ResponseEnum.PARAMETER_ERROR);
        }
        roleService.setAuthority(roleId, permissionIds);
        return success(ResponseEnum.ADD_ROLE_AUTHORITY_SUCCESS);
    }
}
